using System;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using AutoStartManager.Models;

namespace AutoStartManager
{
    public class AddAppDialog : Form
    {
        public ManagedApp ManagedApp { get; private set; }

        private TextBox _nameTextBox;
        private TextBox _pathTextBox;
        private TextBox _argumentsTextBox;
        private TextBox _workingDirectoryTextBox;
        private CheckBox _enabledCheckBox;
        private Button _browseButton;
        private Button _okButton;
        private Button _cancelButton;

        public AddAppDialog(ManagedApp? existingApp = null)
        {
            ManagedApp = existingApp ?? new ManagedApp();
            InitializeComponent();
            LoadExistingApp();
        }

        private void InitializeComponent()
        {
            this.SuspendLayout();

            // 设置窗体属性
            this.Text = ManagedApp.Name == string.Empty ? "添加应用" : "编辑应用";
            this.Size = new Size(500, 400);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 创建主面板
            var mainPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 6,
                Padding = new Padding(10)
            };

            // 设置列宽
            mainPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 100));
            mainPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));

            // 设置行高

            for (int i = 0; i < 6; i++)
            {
                mainPanel.RowStyles.Add(new RowStyle(SizeType.Absolute, 30));
            }

            // 应用名称
            var nameLabel = new Label
            {
                Text = "应用名称:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            _nameTextBox = new TextBox
            {
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };

            // 程序路径
            var pathLabel = new Label
            {
                Text = "程序路径:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            var pathPanel = new TableLayoutPanel
            {
                Dock = DockStyle.Fill,
                ColumnCount = 2,
                RowCount = 1
            };
            pathPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Percent, 100));
            pathPanel.ColumnStyles.Add(new ColumnStyle(SizeType.Absolute, 80));
            
            _pathTextBox = new TextBox
            {
                Dock = DockStyle.Fill,
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };
            _browseButton = new Button
            {
                Text = "浏览...",
                Dock = DockStyle.Fill,
                Margin = new Padding(5, 0, 0, 0)
            };
            _browseButton.Click += BrowseButton_Click;

            pathPanel.Controls.Add(_pathTextBox, 0, 0);
            pathPanel.Controls.Add(_browseButton, 1, 0);

            // 启动参数
            var argumentsLabel = new Label
            {
                Text = "启动参数:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            _argumentsTextBox = new TextBox
            {
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };

            // 工作目录
            var workingDirectoryLabel = new Label
            {
                Text = "工作目录:",
                TextAlign = ContentAlignment.MiddleLeft,
                Anchor = AnchorStyles.Left
            };
            _workingDirectoryTextBox = new TextBox
            {
                Anchor = AnchorStyles.Left | AnchorStyles.Right
            };

            // 启用状态
            _enabledCheckBox = new CheckBox
            {
                Text = "启用监控",
                Checked = true,
                Anchor = AnchorStyles.Left
            };

            // 按钮面板
            var buttonPanel = new FlowLayoutPanel
            {
                Dock = DockStyle.Fill,
                FlowDirection = FlowDirection.RightToLeft,
                Height = 40,
                Padding = new Padding(10, 8, 10, 8)
            };

            _cancelButton = new Button
            {
                Text = "取消",
                Size = new Size(80, 25),
                DialogResult = DialogResult.Cancel
            };
            _cancelButton.Click += CancelButton_Click;

            _okButton = new Button
            {
                Text = "确定",
                Size = new Size(80, 25),
                Margin = new Padding(0, 0, 10, 0)
            };
            _okButton.Click += OkButton_Click;

            // 注意：先添加取消按钮，因为FlowDirection是RightToLeft
            buttonPanel.Controls.Add(_cancelButton);
            buttonPanel.Controls.Add(_okButton);

            // 添加到主面板
            mainPanel.Controls.Add(nameLabel, 0, 0);
            mainPanel.Controls.Add(_nameTextBox, 1, 0);
            mainPanel.Controls.Add(pathLabel, 0, 1);
            mainPanel.Controls.Add(pathPanel, 1, 1);
            mainPanel.Controls.Add(argumentsLabel, 0, 2);
            mainPanel.Controls.Add(_argumentsTextBox, 1, 2);
            mainPanel.Controls.Add(workingDirectoryLabel, 0, 3);
            mainPanel.Controls.Add(_workingDirectoryTextBox, 1, 3);
            mainPanel.Controls.Add(_enabledCheckBox, 1, 4);
            mainPanel.Controls.Add(buttonPanel, 0, 5);
            mainPanel.SetColumnSpan(buttonPanel, 2);

            this.Controls.Add(mainPanel);
            
            // 设置默认按钮
            this.AcceptButton = _okButton;
            this.CancelButton = _cancelButton;
            
            this.ResumeLayout(false);
        }

        private void LoadExistingApp()
        {
            _nameTextBox.Text = ManagedApp.Name;
            _pathTextBox.Text = ManagedApp.ExecutablePath;
            _argumentsTextBox.Text = ManagedApp.Arguments;
            _workingDirectoryTextBox.Text = ManagedApp.WorkingDirectory;
            _enabledCheckBox.Checked = ManagedApp.IsEnabled;
        }

        private void BrowseButton_Click(object? sender, EventArgs e)
        {
            using var openFileDialog = new OpenFileDialog
            {
                Title = "选择可执行文件",
                Filter = "可执行文件 (*.exe)|*.exe|所有文件 (*.*)|*.*",
                FilterIndex = 1
            };

            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                _pathTextBox.Text = openFileDialog.FileName;
                
                // 自动填充工作目录
                if (string.IsNullOrEmpty(_workingDirectoryTextBox.Text))
                {
                    _workingDirectoryTextBox.Text = Path.GetDirectoryName(openFileDialog.FileName);
                }

                // 自动填充应用名称
                if (string.IsNullOrEmpty(_nameTextBox.Text))
                {
                    _nameTextBox.Text = Path.GetFileNameWithoutExtension(openFileDialog.FileName);
                }
            }
        }

        private void OkButton_Click(object? sender, EventArgs e)
        {
            if (ValidateInput())
            {
                ManagedApp.Name = _nameTextBox.Text.Trim();
                ManagedApp.ExecutablePath = _pathTextBox.Text.Trim();
                ManagedApp.Arguments = _argumentsTextBox.Text.Trim();
                ManagedApp.WorkingDirectory = _workingDirectoryTextBox.Text.Trim();
                ManagedApp.IsEnabled = _enabledCheckBox.Checked;

                this.DialogResult = DialogResult.OK;
                this.Close();
            }
        }

        private void CancelButton_Click(object? sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private bool ValidateInput()
        {
            if (string.IsNullOrWhiteSpace(_nameTextBox.Text))
            {
                MessageBox.Show("请输入应用名称", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _nameTextBox.Focus();
                return false;
            }

            if (string.IsNullOrWhiteSpace(_pathTextBox.Text))
            {
                MessageBox.Show("请选择程序路径", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _pathTextBox.Focus();
                return false;
            }

            if (!File.Exists(_pathTextBox.Text))
            {
                MessageBox.Show("指定的程序文件不存在", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _pathTextBox.Focus();
                return false;
            }

            if (!string.IsNullOrWhiteSpace(_workingDirectoryTextBox.Text) && !Directory.Exists(_workingDirectoryTextBox.Text))
            {
                MessageBox.Show("指定的工作目录不存在", "验证错误", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                _workingDirectoryTextBox.Focus();
                return false;
            }

            return true;
        }
    }
}